from flask import Blueprint, jsonify, request
from models.entity.device import Device
import json
from utils.nodetree import get_all_device
from models.entity.device_info import DeviceInfo
from utils.result import result


mod = Blueprint("core_device_info", __name__, url_prefix="/core/device_info", template_folder="templates", static_folder="static")


@mod.route('/add/', methods=['POST'])
def add_device():
    """增加设备更多信息"""
    """
    {
    "device_id":1,
    "weight":"15kg",
    "device_model":"K220111",
    "temperature":"60",
    "pump_num":3,
    "pump_type":"667HV",
    "rated_water":"22285t/m3",
    "control_case_type":"dddd",
    "power":"80W",
    "voltage":"220V",
    "steady_flow_type":"48m3/h",
    "water_distance":"125m",
    "out_size":"25km",
    "all_voltage":"50kw",
    "flow_controler":"22222RE",
    "enhance_pressure":"PPPOP",
    "gas_enhance_pressure":"pppppp",
    "supplement_device":"22222LLL",
    "water_case":"2225G",
    "product_date":"2222223"
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode('utf-8'))
        if "device_id" not in dict:
            return result(success=0,error_code=-1,error_msg='设备没有选择，请选择设备')
        if DeviceInfo.get_info_by_device_id(dict['device_id']):
            return result(success=0,error_code=-1,error_msg='设备信息已经存在，请不要添加')
        device_info = DeviceInfo()
        try:
            device_info.from_dict(dict)
        except RuntimeError as e:
            result(success=0,error_msg=e,error_code=-1)
        if device_info.save():
            return result(success=1)
        else:
            return result(success=0, error_code=-4, error_msg="未知错误")


    """
    {
    "id":1
    "device_id":1,
    "weight":"15kg",
    "device_model":"K220111",
    "temperature":"60",
    "pump_num":3,
    "pump_type":"667HV",
    "rated_water":"22285t/m3",
    "control_case_type":"dddd",
    "power":"80W",
    "voltage":"220V",
    "steady_flow_type":"48m3/h",
    "water_distance":"125m",
    "out_size":"25km",
    "all_voltage":"55kw",
    "flow_controler":"22222RE",
    "enhance_pressure":"PPPOP",
    "gas_enhance_pressure":"pppppp",
    "supplement_device":"22222LLL",
    "water_case":"2225G",
    "product_date":"2222223"
    }
    """

@mod.route('/get/', methods=['POST'])
def get_device():
    """得到设备信息"""
    if request.method == 'POST':
        dict = json.loads(request.data.decode('utf-8'))
        data=[]
        if "device_id" not in dict:
            return result(success=0,error_code=-1,error_msg='信息有错误，修改失败')
        device_id = dict['device_id']
        device_info = DeviceInfo.get_info_by_device_id(device_id)
        if not device_info:
            return result(success=0,error_code=-1,error_msg='指定设备不存在')
        return result(data=[device_info.to_dict()])




@mod.route('/edit/', methods=['GET', 'POST'])
def edit_device():
    """编辑设备信息"""
    if request.method == 'POST':
        tmp = {}
        dict = json.loads(request.data.decode('utf-8'))
        data=[]
        if "id" not in dict:
            return result(success=0,error_code=-1,error_msg='信息有错误，修改失败',data=data)
        id = dict['id']
        device_id = dict['device_id']
        device_info = DeviceInfo.get_device_info_by_id(id)
        print(device_info)
        device_info.from_dict(dict)
        if device_info.save():
            return result(success=1)
        else:
            return result(success=0,error_code=-4,error_msg="未知错误")


@mod.route('/del/', methods=['GET', 'POST'])
def del_device():
    """删除设备信息"""
    """
    {
    "id":2
    }
    """
    if request.method == 'POST':
        tmp = {}
        data=[]
        receive = request.data
        dict = json.loads(receive.decode('utf-8'))
        id = dict['id']
        if not Device.query.filter_by(id =id).first():
            return result(success=0,error_msg='对应的设备信息不存在',error_code=-1)
        device = Device.query.filter_by(id=id).first()
        # 下面开始删除
        if device.delete():
            return result(success=1)
        else:
            return result(success=0,error_msg='未知错误',error_code=-3)


@mod.route("/search/",methods=["POST"])
def search_device():
    """
    查询设备信息
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode('utf-8'))
        tmp ={}
        extra =[]
        if 'query_word' in dict:
            query_word = dict['query_word']
        else:
            tmp['success'] = 0
            tmp['error_code'] = -9
            tmp['error_msg'] = "数据格式错误"
            tmp['data'] = extra
            return result(success=0,error_code=-9,error_msg='数据格式错误')
        device_info = DeviceInfo.search(query_word)
        return result(success=1,data=device_info)